#!/bin/bash

trap 'rm -f ${cve_file}' SIGINT SIGTERM SIGQUIT SIGHUP
set -ex
set -o pipefail

#proxy="http://127.0.0.1:8889"
if [ $proxy ];then
	CURLCMD="curl -x $proxy"
else
	CURLCMD="curl"
fi
	


NVD_BASE_URL="https://nvd.nist.gov/feeds/json/cve/1.1"
DEBIAN_URL="https://security-tracker.debian.org/tracker/data/json"
CURDIR=$(dirname `type -p $0`)

function get_NVD {
	meta_file_url="${NVD_BASE_URL}/nvdcve-1.1-${1}.meta"
	cve_file_url="${NVD_BASE_URL}/nvdcve-1.1-${1}.json.gz"

	checksum=$(${CURLCMD} -sfL $meta_file_url | sed -n 's/^sha256://p' | tr -d '\r')
	cve_file=$(mktemp)
	echo '获取'$1'年CVE....' && ${CURLCMD} -#L $cve_file_url | gzip -cd > $cve_file
	sha256sum -c <<< "$checksum $cve_file"
	$CURDIR/fetch_NVD_score $cve_file

	rm $cve_file
}

#------------清理工作目录---------------------------
echo "清除工作目录..." && rm -vf $CURDIR/transit/*

#------------获取debian漏洞信息-----------------
echo "开始获取debian CVE..."
source_file="${CURDIR}/input/json"
if [ -e ${source_file} ]
then
	echo "提取本地debian CVE信息 ..."
	$CURDIR/debian_pkg_CVE ${source_file}
else
	echo "爬取security-tracker.debian.org漏洞信息..."
	cve_file=$(mktemp)
	${CURLCMD} -#L ${DEBIAN_URL} > $cve_file
	#curl -#L ${DEBIAN_URL} > $cve_file
	echo "正在提取debian CVE信息..."
	$CURDIR/debian_pkg_CVE $cve_file
fi
echo "提取debian CVE信息完成！"

#------------提取NVD CVE信息-----------------
echo "开始获取NVD CVE..."
for year in $(seq 2002 `date +%Y`)
do
	get_NVD $year 
done

get_NVD "modified"
get_NVD "Recent"
echo "获取NVD CVE完成！"

#------------合并debian漏洞和nvd漏洞信息-----------------
echo "开始合成漏洞信息..."
$CURDIR/integrate_CVE_info   #合成需要的CVE信息
echo "合并完成！"

#------------发送更新漏洞请求-----------------
echo "发送更新请求..."
$CURDIR/get_token.py
echo "发送请求完成！"
#echo "正在推送远端仓库..."
#$CURDIR/sync-git.sh  #推送远端
